import {
  CLASSES,
  NUM_CLASSES,
  NUM_CHANNELS,
  NUM_DATASET_ELEMENTS,
  IMAGE_SIZE,
  IMAGE_WIDTH,
  IMAGE_HEIGHT,
  IMAGE_WIDTH_2,
  IMAGE_HEIGHT_2,
  font,
} from "./OCRDatasetConstants";
import { type WorkerMessage } from "@/renderer/utils/Worker";

function createImagesDataset() {
  const canvas = new OffscreenCanvas(IMAGE_WIDTH, IMAGE_HEIGHT);
  const datasetBytesBuffer = new ArrayBuffer(
    NUM_DATASET_ELEMENTS * IMAGE_SIZE * NUM_CHANNELS * 1
  ); // NUM_DATASET_ELEMENTS * IMAGE_SIZE * byte * NUM_CHANNELS； Uint8Array 1字节，Uint16Array 2字节， Float32Array 4字节
  const datasetTypedArray = new Uint8Array(
    datasetBytesBuffer,
    0,
    NUM_DATASET_ELEMENTS * IMAGE_SIZE * NUM_CHANNELS
  );
  const ctx = canvas.getContext("2d");

  canvas.width = IMAGE_WIDTH;
  canvas.height = IMAGE_HEIGHT;

  function clear() {
    ctx.fillStyle = "#000";
    ctx.fillRect(0, 0, IMAGE_WIDTH, IMAGE_HEIGHT);
  }

  function write(str, font) {
    ctx.fillStyle = "#fff";
    ctx.font = font;
    ctx.textAlign = "center";
    ctx.textBaseline = "middle";
    ctx.fillText(str, IMAGE_WIDTH_2, IMAGE_HEIGHT_2);
  }

  for (const i in font) {
    const ft = font[i];

    for (const j in CLASSES as any) {
      clear();
      write(CLASSES[j], ft);

      const data = ctx.getImageData(0, 0, IMAGE_WIDTH, IMAGE_HEIGHT).data;

      datasetTypedArray.set(
        data,
        (Number(i) * NUM_CLASSES + Number(j)) * IMAGE_SIZE * NUM_CHANNELS
      );
    }

    globalThis.postMessage({
      type: 'createImagesDatasetProgress',
      data: Math.floor(((Number(i) + 1) / font.length) * 100)
    });
  }

  return datasetTypedArray;
}

globalThis.onmessage = (event) => {
  const message: WorkerMessage = event.data;
  const { type, UUID } = message;
  let data;
  const resultMessage: WorkerMessage = { UUID, type, data };
  
  if (type == "createImagesDataset") resultMessage.data = createImagesDataset();

  globalThis.postMessage(resultMessage);
};
